using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Log;
using GrapeCity.Forguncy.Plugin;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace FaissOperation
{
    [Icon("pack://application:,,,/FaissOperation;component/Resources/Icon.png")]
    [Designer("FaissOperation.Designer.FaissOperationServerCommandDesigner, FaissOperation")]
    [Category("嵌入式向量索引")]
    [OrderWeight(910)]
    public class VKB_Save : Command, ICommandExecutableInServerSideAsync
    {
        [FormulaProperty]
        [DisplayName("集合名")]
        public object KBName { get; set; }


        [DisplayName("将导出结果保存到变量")]
        [Description("本方法因性能较差，已经过时，请使用【持久化向量集合】代替。")]
        [ResultToProperty]
        public string ResultInParamater { get; set; } = "JSON";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var name = (await dataContext.EvaluateFormulaAsync(KBName))?.ToString() ?? "";

            if (string.IsNullOrEmpty(name) || !CollectionManager.Instance.CollectionExists(name))
            {
                throw new Exception("当前向量集合尚未被加载，请先调用【加载向量集合】然后执行本操作。");
            }

            // 获取集合的数据
            var collection = CollectionManager.Instance.GetCollection(name);
            var data = collection.GetData();

            // 处理为兼容的格式
            ConcurrentDictionary<int, float[]> map = new ConcurrentDictionary<int, float[]>();

            for (int i = 0; i < data.Ids.Count; i++)
            {
                map.TryAdd(data.Ids[i], data.Vectors[i]);
            }

            // 将集合数据转换为JSON字符串
            var json = JsonSerializer.Serialize(map.ToDictionary(kv => kv.Key, kv => kv.Value));

            // 返回JSON字符串到参数中
            dataContext.Parameters[ResultInParamater] = json;

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "将向量集合转换为JSON（已过时）";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }


    }
}
